﻿using AutoMapper;
using MediatR;
using Reporting.API.Application.Commands.Productionorders;
using Reporting.Errorcode;
using Reporting.Errorcode.ErrorCode;
using Reporting.Infrastructure.Interfaces.Productionorders;

namespace Reporting.API.Application.CommandHandler.Productionorders
{
    public class DeleteProductionorderCommandHandler : IRequestHandler<DelProductionCommand, ApiResult>
    {
        private readonly IProductionorderRepository _productionorderRepository;
        private readonly IMapper _mapper;
        private readonly ILogger<DeleteProductionorderCommandHandler> _logger;

        public DeleteProductionorderCommandHandler(ILogger<DeleteProductionorderCommandHandler> logger, IMapper mapper, IProductionorderRepository productionorderRepository)
        {
            _logger = logger;
            _mapper = mapper;
            _productionorderRepository = productionorderRepository;
        }

        public async Task<ApiResult> Handle(DelProductionCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // id查询生产工单
                var Productionorderselect = await _productionorderRepository.GetAsync(x => x.Productionorderid == request.Productionorderid);
                if (Productionorderselect == null)
                {
                    return ApiResult.Fail("删除失败，当前数据不存在", StatusCodeEnum.BadRequest);
                }
                // 删除生产工单
                var result = await _productionorderRepository.DeleteAsync(Productionorderselect);
                return ApiResult.Success(StatusCodeEnum.Success);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "生产工单删除失败");
                throw;
            }
        }
    }
}
